package com.yupi.project.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yupi.project.common.ErrorCode;
import com.yupi.project.exception.BusinessException;
import com.yupi.project.mapper.UserMapper;
import com.yupi.project.service.EmailService;
import com.yupi.project.util.EmailUtil;
import com.yupi.yuapicommon.model.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.yupi.project.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author <a href=""https://github.com/Fzs0>逢左使</a>
 * @create 2023/12/27 11:23
 * @Description: 邮箱验证码服务
 */
@Service
public class EmailServiceImpl implements EmailService {

    @Resource
    private UserMapper userMapper;

    private static final String SALT = "HP";

    /**
     * 用户邮箱登录
     *
     * @param email
     * @param request
     */
    @Override
    public User userLoginByEmail(String email, HttpServletRequest request) {
        // 1.查看数据库是否存有对应的邮箱
        // 1.1 校验
        if (StringUtils.isAnyBlank(email)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        User user = userMapper.selectOne(queryWrapper);
        // 2.1 如果不存在 则添加一条邮箱所对应的用户 用户账号随机初始化
        if (user == null) {
            user = new User();
            // 生成的随机账号
            String userAccount = EmailUtil.generateRandomAccount();
            // 生成的随机密码
            String encryptPassword = EmailUtil.generateDefaultEncryptPassword();
            // 分配 accessKey, secretKey
            String accessKey = DigestUtil.md5Hex(SALT + userAccount + RandomUtil.randomNumbers(5));
            String secretKey = DigestUtil.md5Hex(SALT + userAccount + RandomUtil.randomNumbers(8));
            // 4. 插入数据
            user.setUserAccount(userAccount);
            user.setUserPassword(encryptPassword);
            user.setAccessKey(accessKey);
            user.setSecretKey(secretKey);
            user.setEmail(email);
            int saveResult = userMapper.insert(user);
            if (saveResult < 1) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }
        }
        // 2.2 如果存在 查出对应的 user 数据存入登录态中
        request.getSession().setAttribute(USER_LOGIN_STATE, user);
        return user;
    }
}
